import { useState } from 'react';

interface DiffResult {
  type: 'add' | 'remove' | 'equal';
  value: string;
}

interface CompareResult {
  lineDiffs: DiffResult[][];
  totalAdded: number;
  totalRemoved: number;
  totalEqual: number;
}

export const useTextCompare = () => {
  const [text1, setText1] = useState('');
  const [text2, setText2] = useState('');
  const [compareResult, setCompareResult] = useState<CompareResult | null>(null);
  const [error, setError] = useState('');
  const [compareMode, setCompareMode] = useState<'line' | 'character'>('line');

  // Compare the two texts
  const compareTexts = () => {
    if (!text1.trim() && !text2.trim()) {
      setError('请输入要比较的文本');
      setCompareResult(null);
      return;
    }

    try {
      if (compareMode === 'line') {
        compareLineByLine();
      } else {
        compareCharByChar();
      }
      setError('');
    } catch (err) {
      setError('比较文本时出错');
      setCompareResult(null);
    }
  };

  // Line by line comparison
  const compareLineByLine = () => {
    const lines1 = text1.split('\n');
    const lines2 = text2.split('\n');
    
    const result: DiffResult[][] = [];
    let totalAdded = 0;
    let totalRemoved = 0;
    let totalEqual = 0;

    // Simple diff algorithm (can be improved with LCS algorithm)
    const maxLen = Math.max(lines1.length, lines2.length);
    
    for (let i = 0; i < maxLen; i++) {
      const line1 = i < lines1.length ? lines1[i] : '';
      const line2 = i < lines2.length ? lines2[i] : '';
      
      const lineDiff: DiffResult[] = [];
      
      if (line1 === line2) {
        lineDiff.push({ type: 'equal', value: line1 });
        totalEqual++;
      } else {
        if (line1) {
          lineDiff.push({ type: 'remove', value: line1 });
          totalRemoved++;
        }
        if (line2) {
          lineDiff.push({ type: 'add', value: line2 });
          totalAdded++;
        }
      }
      
      result.push(lineDiff);
    }

    setCompareResult({
      lineDiffs: result,
      totalAdded,
      totalRemoved,
      totalEqual
    });
  };

  // Character by character comparison
  const compareCharByChar = () => {
    // Group by lines for display
    const lines1 = text1.split('\n');
    const lines2 = text2.split('\n');
    
    const result: DiffResult[][] = [];
    let totalAdded = 0;
    let totalRemoved = 0;
    let totalEqual = 0;

    const maxLen = Math.max(lines1.length, lines2.length);
    
    for (let i = 0; i < maxLen; i++) {
      const line1 = i < lines1.length ? lines1[i] : '';
      const line2 = i < lines2.length ? lines2[i] : '';
      
      const chars1 = line1.split('');
      const chars2 = line2.split('');
      const lineDiff: DiffResult[] = [];
      
      if (line1 === line2) {
        lineDiff.push({ type: 'equal', value: line1 });
        totalEqual += line1.length;
      } else {
        // Find character differences
        const maxCharLen = Math.max(chars1.length, chars2.length);
        let curr1 = '';
        let curr2 = '';
        
        for (let j = 0; j < maxCharLen; j++) {
          const char1 = j < chars1.length ? chars1[j] : '';
          const char2 = j < chars2.length ? chars2[j] : '';
          
          if (char1 === char2) {
            if (curr1) {
              lineDiff.push({ type: 'remove', value: curr1 });
              totalRemoved += curr1.length;
              curr1 = '';
            }
            if (curr2) {
              lineDiff.push({ type: 'add', value: curr2 });
              totalAdded += curr2.length;
              curr2 = '';
            }
            lineDiff.push({ type: 'equal', value: char1 });
            totalEqual++;
          } else {
            if (char1) curr1 += char1;
            if (char2) curr2 += char2;
          }
        }
        
        // Add any remaining differences
        if (curr1) {
          lineDiff.push({ type: 'remove', value: curr1 });
          totalRemoved += curr1.length;
        }
        if (curr2) {
          lineDiff.push({ type: 'add', value: curr2 });
          totalAdded += curr2.length;
        }
      }
      
      result.push(lineDiff);
    }

    setCompareResult({
      lineDiffs: result,
      totalAdded,
      totalRemoved,
      totalEqual
    });
  };

  // Copy result as text
  const copyAsText = () => {
    if (!compareResult) return false;
    
    const { lineDiffs } = compareResult;
    const textContent = lineDiffs.map(line => {
      return line.map(diff => {
        if (diff.type === 'add') {
          return `+ ${diff.value}`;
        } else if (diff.type === 'remove') {
          return `- ${diff.value}`;
        } else {
          return `  ${diff.value}`;
        }
      }).join('\n');
    }).join('\n');
    
    navigator.clipboard.writeText(textContent);
    return true;
  };

  // Copy result as HTML
  const copyAsHTML = () => {
    if (!compareResult) return false;
    
    const { lineDiffs } = compareResult;
    const htmlContent = `
<div class="diff-container">
  ${lineDiffs.map(line => `
  <div class="diff-line">
    ${line.map(diff => {
      if (diff.type === 'add') {
        return `<span class="diff-add">${diff.value}</span>`;
      } else if (diff.type === 'remove') {
        return `<span class="diff-remove">${diff.value}</span>`;
      } else {
        return `<span class="diff-equal">${diff.value}</span>`;
      }
    }).join('')}
  </div>`).join('')}
</div>`;
    
    navigator.clipboard.writeText(htmlContent);
    return true;
  };

  // Load example data
  const loadExample = () => {
    setText1(`这是一段示例文本。
它有多行内容。
这行将被修改。
这行将保持不变。
这行将被删除。
最后一行。`);

    setText2(`这是一段示例文本。
它有多行内容。
这行已被修改为新内容。
这行将保持不变。
这是新增的一行。
最后一行。`);
  };

  // Clear both text inputs
  const clearTexts = () => {
    setText1('');
    setText2('');
    setCompareResult(null);
    setError('');
  };

  return {
    text1,
    text2,
    setText1,
    setText2,
    compareResult,
    error,
    compareMode,
    setCompareMode,
    compareTexts,
    copyAsText,
    copyAsHTML,
    loadExample,
    clearTexts
  };
}; 